import { __private, _decorator, Component, Node } from 'cc';

//多模块继承
// export class customEvent<T>{

//单例事件注册类
export class customEvent{
    private static instance: any = null;
    private eventList = new Map<string, EventStruct>()
    
    // 为多模块继承使用泛型继承
    // public static GetInstance<T>(c: { new(): T }): T {
    //     if (this.instance == null) {
    //         this.instance = new c();
    //     }
    //     return this.instance;
    // }
    //获取实例
    public static GetInstance():customEvent{
        if (this.instance == null) {
            this.instance = new customEvent();
        }
        return this.instance;
    }
    /**
     * 注册事件
     * 
     * @param type 事件类型 string
     * @param func 回调方法 method  注：(data: any) => void仅是一个方法体，没有任何访问权限，即仅能在单独的作用域中执行代码
     * @param requiresArguments 是否需要传参
     * @returns void
     * 
     */
    public register(type: string, func: __private._types_globals__AnyFunction, requiresArguments: boolean,target:any) {
        if (this.eventList.get(type)) {
            this.eventList[type].push(new EventStruct(func,requiresArguments,target))
            return;
        }
        if (!this.eventList[type]) {
            this.eventList[type] = []
        }
        this.eventList[type].push(new EventStruct(func, requiresArguments,target))
    }
    /**
     * 注销事件
     * 
     * @param type 事件类型 string
     * @param func 回调方法 method
     * @param requiresArguments 是否需要传参
     */
    logout(type: string, func:  __private._types_globals__AnyFunction, requiresArguments,target:any) {
        if (func == null) {
            this.eventList[type] = []
        } else {
            let index = this.eventList[type].indexOf(new EventStruct(func, requiresArguments,target))
            this.eventList[type].splice(index, 1)
        }
    }
    /**
     * 触发事件
     * 
     * @param type 事件类型 string
     * @param args 参数列表 可空
     * @returns void
     */
    emit(type, ...args: any[]) {
        for (const event of this.eventList[type]) {
            if (event.requiresArguments && args.length) {
                event.callback.apply(event.target,args);
            } else if(!event.requiresArguments && !args.length) {
                event.callback.apply(event.target);
            }else{
                // return;
            }
        }
    }
}
//注册事件类型
export class customEventType {
    public static OVER_LOAD: string = "customEvent.OVER_LOAD"
    public static HASBEEN_CREATE:string ="customEvent.HASBEEN_CREATE"
}

//注册事件结构体
class EventStruct {
    callback:  __private._types_globals__AnyFunction;
    requiresArguments: boolean;
    target:any
    constructor(callback:  __private._types_globals__AnyFunction,requiresArguments: boolean,target:any){
        this.callback=callback;
        this.requiresArguments=requiresArguments;
        this.target=target;
    }
}